package com.java.socket.udp.singleclient.server;

import java.io.IOException;
import java.net.*;
import java.nio.charset.Charset;

/**
 * UDP协议下的单个客户端网络通信.
 * <p>服务器端实例</p>
 *
 * @author xzmeasy
 * @version 1.0
 * @since 星期一 十二月,2018
 */
@SuppressWarnings("Duplicates")
public class DatagramServerExample {

    public static void main(String[] args) {
        try {
            // 创建DatagramSocket，监听指定端口
            DatagramSocket datagramSocket = new DatagramSocket(8888);
            // 创建DatagramPacket，用于保存接收到的数据包
            byte[] bytes = new byte[1024];
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
            // 调用receive()方法接收数据包
            datagramSocket.receive(packet);
            String data = new String(packet.getData(), Charset.forName("utf-8"));
            System.out.println("接收到的数据: " + data + ", 数据来自" + packet.getSocketAddress().toString());
            // 关闭DatagramSocket
            datagramSocket.close();


            // 接收方的数据
            DatagramSocket socket = new DatagramSocket();
            byte[] bytes1 = "接收方的反馈数据".getBytes();
            DatagramPacket sendPacket = new DatagramPacket(bytes1, bytes1.length);
            sendPacket.setAddress(InetAddress.getByName("localhost"));
            // 端口号不能与上面一致，因为上面的端口已经被占用
            sendPacket.setPort(8889);
            // 发送反馈数据
            socket.send(sendPacket);
            // 关闭socket
            socket.close();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
